package com.project.api.ym.dao;

import com.project.api.ym.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class UserDao {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    @Qualifier("mainJdbcTemplate")
    private JdbcTemplate mainJdbcTemplate;


    public User GetUserById(long id){
        User res=new User();
        String sql = "SELECT * FROM "+ User.tableName +" where `id`=?";
        try {
            res = (User) mainJdbcTemplate.queryForObject(
                    sql, new Object[] {id},new BeanPropertyRowMapper(User.class));
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
            return res;
        }
        return res;
    }

    public int GetUserCount(String condition){
        String sql = "select count(*) from "+User.tableName;
        if (condition!=null && !condition.equalsIgnoreCase("")){
            sql=sql+" where 1=1 "+condition;
        }
        int count = mainJdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }

    public List<User> GetUser(String condition){
        List<User> res = new ArrayList<>();
        String sql = "SELECT * FROM "+ User.tableName ;
        if (condition!=null && !condition.equalsIgnoreCase("")){
            sql=sql+" where 1=1 "+condition;
        }
        try {
            res = mainJdbcTemplate.query(
                    sql, new Object[] {},new BeanPropertyRowMapper(User.class));
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
            return res;
        }
        return res;
    }
}
